package com.cvtt.common;

import java.security.Key;
import java.security.MessageDigest;
import java.util.Map;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;

public class EncryptUtil {

	public static final String ALGORITHM_DES = "DES/ECB/PKCS7Padding";
	public final static String xmppServKey = "24c78d59";	//XMPP通讯录上传加密Key
	public final static String xmppServIv = "37ed6548";		//XMPP通讯录上传加密偏移向量

	private static String byteArrayToHexString(byte[] byteArray) {
		StringBuffer resultSb = new StringBuffer();

		for (int i = 0; i < byteArray.length; i++) {
			String hexStr = Integer.toHexString(0xFF & byteArray[i]);
			if (hexStr.length() == 1)
				resultSb.append("0").append(hexStr);
			else
				resultSb.append(hexStr);
		}

		return resultSb.toString();
	}

	private static byte[] md5Digest(String str) {
		MessageDigest md = null;

		try {
			md = MessageDigest.getInstance("MD5");

			md.reset();

			md.update(str.getBytes("UTF-8"));

			return md.digest();

			// return md.digest(str.getBytes("UTF-8"));
		}
		catch (Exception e) {
			// System.out.println("NoSuchAlgorithmException caught!");
			// System.exit(-1);
			return null;
		}
	}

	public static String MD5(String str) {

		byte[] byteArray = md5Digest(str);

		if (byteArray == null)
			return null;

		return byteArrayToHexString(byteArray);
	}

	public static String desEncode(String key, String data) throws Exception {

		try {
			// DESKeySpec dks = new DESKeySpec(key.getBytes());
			DESKeySpec dks = new DESKeySpec(Base64.decode(key));
			SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
			// key的长度不能够小于8位字节
			Key secretKey = keyFactory.generateSecret(dks);
			Cipher cipher = Cipher.getInstance(ALGORITHM_DES);
			// IvParameterSpec iv = new IvParameterSpec(ivByte);
			// AlgorithmParameterSpec paramSpec = iv;
			// cipher.init(Cipher.ENCRYPT_MODE, secretKey, paramSpec);
			cipher.init(Cipher.ENCRYPT_MODE, secretKey);
			byte[] bytes = cipher.doFinal(Base64.decode(data));
			return Base64.encodeBytes(bytes);
		}
		catch (Exception e) {
			throw new Exception(e);
		}
	}

	public static String makeSign(Map<String, String> params, String signKey) {
		String result = null;
		String[] items = new String[params.size()];
		int i = 0;
		for (String key : params.keySet()) {
			items[i] = key + signKey + params.get(key);
			i++;
		}

		do {
			if (items == null || items.length < 1 || items[0] == null || items[0].length() == 0) {
				break;
			}

			byte[] bFirestItem = md5Digest(items[0]);

			for (i = 1; i < items.length; i++) {
				if (items[i] == null || items[i].length() == 0) {
					continue;
				}
				byte[] bItem = md5Digest(items[i]);
				for (int j = 0; j < bFirestItem.length; j++) {
					bFirestItem[j] = (byte) ((int) bFirestItem[j] ^ (int) bItem[j]);
				}
			}

			result = byteArrayToHexString(bFirestItem);
		}
		while (false);
		return result;
	}

	/**
	 * DES解密，用于XMPPServer通讯录传输
	 * 
	 * */
	public static String desDecode(String data) throws Exception {
		try {
			IvParameterSpec zeroIv = new IvParameterSpec(xmppServIv.getBytes());
			byte[] enStr = Base64.decode(data);
			
			
			//Log.e("decode", byteArrayToHexString(enStr));
			DESKeySpec dks = new DESKeySpec(xmppServKey.getBytes());
			SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
			// key的长度不能够小于8位字节
			Key secretKey = keyFactory.generateSecret(dks);
			Cipher cipher = Cipher.getInstance("DES/CBC/NoPadding");
			
			cipher.init(Cipher.DECRYPT_MODE, secretKey, zeroIv);
			byte[] bytes = cipher.doFinal(enStr);

			return (new String(bytes)).replace('\0', ' ').trim();
		}
		catch (Exception e) {
			throw new Exception(e);
		}
	}
	
	/**
	 * DES加密用，用于不满8位时填充0使用
	 * 
	 * */
	private static byte [] fillDataZero(String data)
	{
		byte [] dataStr = data.getBytes();
		int data_length = dataStr.length;
		int endata_length = data_length;
		if((data_length%8) == 0)
			endata_length = data_length;
		else
			endata_length = data_length + (8 - (dataStr.length%8));
		
		byte [] dataStr2 = new byte [endata_length];

		for (int i= 0; i < endata_length; i++)
			dataStr2[i] = 0;

		for (int i= 0; i < data_length; i++)
			dataStr2[i] = dataStr[i];
		return dataStr2;
	}
	
	/**
	 * DES加密，用于XMPPServer通讯录传输
	 * 
	 * */
	public static String desEncode(String data) throws Exception {
		try {
			byte [] dataStr = fillDataZero(data);
			
			IvParameterSpec zeroIv = new IvParameterSpec(xmppServIv.getBytes());
			DESKeySpec dks = new DESKeySpec(xmppServKey.getBytes());
			SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
			// key的长度不能够小于8位字节
			Key secretKey = keyFactory.generateSecret(dks);
			Cipher cipher = Cipher.getInstance("DES/CBC/NoPadding");

			cipher.init(Cipher.ENCRYPT_MODE, secretKey, zeroIv);
			byte[] bytes = cipher.doFinal(dataStr);
			//Log.e("encode", byteArrayToHexString(bytes));
			return Base64.encodeBytes(bytes);
		}
		catch (Exception e) {
			throw new Exception(e);
		}
	}

	
}
